﻿using System;

namespace LxBasic
{
    public struct RMSResidualTool
    {
        public RMSResidualTool()
        {
            SquareSum = 0;
            MaxValue = double.NegativeInfinity;
            MinValue = double.PositiveInfinity;
        }
        public RMSResidualTool(double firstPhi)
        {
            MaxValue = MinValue = firstPhi;
            SquareSum = 0;
        }
        public Float128 SquareSum;
        public double MaxValue;
        public double MinValue;

        private void setMax(double newMax)
        {
            if (newMax > MaxValue) { MaxValue = newMax; }
        }
        private void setMin(double newMin)
        {
            if (newMin < MinValue) { MinValue = newMin; }
        }
        public void Include(double nowValue, double futureValue)
        {
            double temp = nowValue - futureValue;
            SquareSum += temp * temp;
            if (nowValue < futureValue)
            {
                setMax(futureValue);
                setMin(nowValue);
            }
            else
            {
                setMax(nowValue);
                setMin(futureValue);
            }
        }
        public void Include(RMSResidualTool another)
        {
            SquareSum += another.SquareSum;
            setMax(another.MaxValue);
            setMin(another.MinValue);
        }
        public double GetRMS(int n)
        {
            return Math.Sqrt((double)SquareSum / n) / (MaxValue - MinValue + 1e-100);
        }
    }
}

